package com.demo.entity;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

public class RetryInterceptor implements Interceptor {
    private int maxRetries;

    public RetryInterceptor(int maxRetries) {
        this.maxRetries = maxRetries;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = null;
        IOException ioException = null;
        for(int i = 0; i <= maxRetries; i++){
            try {
                response = chain.proceed(request);
                if(response.isSuccessful()){
                    return response;
                }
            } catch (IOException e) {
                ioException = e;
            }
        }
        if(ioException != null){ throw ioException;}
        return response;
    }
}
